﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ARR.UI.Models;
using System.Windows.Input;
using ARR.UI.Commands;
using ARR.Shared;
using System.Collections.ObjectModel;
using ARR.Entities;
using System.Windows;
using ARR.UI.EnvoyImporterService;
using ARR.UI.ExcelImporterService;
using ARR.UI.StoresService;
using System.ServiceModel;

namespace ARR.UI.ViewModels
{
    class StoresImporterViewModel : WorkspaceViewModel
    {
        public IStoresImporterModel model;
        private ICommand cancelCommand;
        private ICommand nextCommand;
        private ICommand retryCommand;
        private ICommand saveCommand;
        private ICommand startCommand;



        public StoresImporterViewModel(IStoresImporterModel model)
        {
            base.DisplayName = Labels.ImportadorDeTiendas;
            this.model = model;

            //TODO: chequear si existen registros en la tabla TempStores
            if (WorkspaceData.Instance.Country.IsStoreMasterSeparateFile)
            {
                CurrentStep = 0;
                HasPassedCurrentStep = null;
            }
            else
            {
                CurrentStep = 1;
                HasPassedCurrentStep = true;
                Step1ImagePath = "/Images/Pass-16.png";
                OnPropertyChanged<StoresImporterViewModel>(p => p.HasPassedCurrentStep);
                CurrentStep = 2;
                HasPassedCurrentStep = true;
                Step2ImagePath = "/Images/Pass-16.png";
                OnPropertyChanged<StoresImporterViewModel>(p => p.HasPassedCurrentStep);
            }
        }




        public ICommand NextCommand
        {
            get
            {
                if (nextCommand == null)
                {
                    nextCommand = new RelayCommand(param => NextStep(), p => (HasPassedCurrentStep.HasValue && HasPassedCurrentStep.Value && CurrentStep < 4));
                }
                return nextCommand;
            }
        }

        public ICommand RetryCommand
        {
            get
            {
                if (retryCommand == null)
                {
                    retryCommand = new RelayCommand(param => RetryCurrentStep(), p => (HasPassedCurrentStep.HasValue && !HasPassedCurrentStep.Value));
                }
                return retryCommand;
            }
        }

        public ICommand StartCommand
        {
            get
            {
                if (startCommand == null)
                {
                    startCommand = new RelayCommand(param => NextStep(), p => CurrentStep == 0);

                }
                return startCommand;
            }
        }

        public ICommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new RelayCommand(param => Save());
                }
                return saveCommand;
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new RelayCommand(param => Cancel());
                }
                return cancelCommand;
            }
        }


        public ObservableCollection<ImporterResult> Results
        {
            get
            {
                return new ObservableCollection<ImporterResult>(model.Results.OrderBy(x => x.Description));
            }
        }

        public ObservableCollection<TempStore> TempStores
        {
            get
            {
                return model.TempStores;
            }
        }

        public Visibility IsVisibleResultsGV
        {
            get
            {
                if (Results != null && Results.Any())
                {
                    return Visibility.Visible;
                }

                return Visibility.Collapsed;
            }
        }

        public Visibility IsVisibleTempStoresGV
        {
            get
            {
                if (TempStores != null && TempStores.Any())
                {
                    return Visibility.Visible;
                }

                return Visibility.Collapsed;
            }
        }

        public string Step1ImagePath { get; set; }

        public string Step2ImagePath { get; set; }

        public string Step3ImagePath { get; set; }

        public string Step4ImagePath { get; set; }

        public int CurrentStep { get; set; }

        public bool? HasPassedCurrentStep { get; set; }

        public bool IsBusy { get; set; }



        public void TriggerPropertyChanged()
        {
            OnPropertyChanged<StoresImporterViewModel>(p => p.TempStores);
        }



        private void Save()
        {
            if (AreValid())
            {
                model.Save();
                RetryCurrentStep();
            }
        }

        private bool AreValid()
        {
            foreach (TempStore store in model.TempStoresCache)
            {
                if (!store.IsValid)
                    return false;
            }

            return true;
        }

        private void Cancel()
        {
            RetryCurrentStep();
        }

        private void NextStep()
        {
            switch (CurrentStep)
            {
                case 0:
                    RunStep1();
                    break;
                case 1:
                    RunStep2();
                    break;
                case 2:
                    RunStep3();
                    break;
                case 3:
                    RunStep4();
                    break;
            }


            OnPropertyChanged<StoresImporterViewModel>(p => p.Results);
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsVisibleResultsGV);

            if (CurrentStep < 4)
                CurrentStep += 1;
        }

        private void RetryCurrentStep()
        {
            CurrentStep -= 1;
            NextStep();
        }


        private void RunStep1()
        {
            switch (WorkspaceData.Instance.Country.StoresImporter)
            {
                case Constants.ImportSettings.StandardExcelImporter:
                    {
                        IsBusy = true;
                        ExcelImporterServiceClient excelService = new ExcelImporterServiceClient();

                        try
                        {
                            excelService.ImportStoreMasterStep1Completed += new EventHandler<ExcelImporterService.ImportStoreMasterStep1CompletedEventArgs>(excelService_ImportStoreMasterStep1Completed);
                            excelService.ImportStoreMasterStep1Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            excelService.Abort();
                            throw ex;
                        }

                        break;
                    }
                case Constants.ImportSettings.EnvoyImporter:
                    {
                        IsBusy = true;
                        EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

                        try
                        {
                            envoyService.ImportStoreMasterStep1Completed += new EventHandler<EnvoyImporterService.ImportStoreMasterStep1CompletedEventArgs>(envoyService_ImportStoreMasterStep1Completed);
                            envoyService.ImportStoreMasterStep1Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            envoyService.Abort();
                            throw ex;
                        }

                        break;
                    }
            }


            OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
        }

        private void RunStep2()
        {
            switch (WorkspaceData.Instance.Country.StoresImporter)
            {
                case Constants.ImportSettings.StandardExcelImporter:
                    {
                        IsBusy = true;

                        ExcelImporterServiceClient excelService = new ExcelImporterServiceClient();

                        try
                        {
                            excelService.ImportStoreMasterStep2Completed += new EventHandler<ExcelImporterService.ImportStoreMasterStep2CompletedEventArgs>(excelService_ImportStoreMasterStep2Completed);
                            excelService.ImportStoreMasterStep2Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            excelService.Abort();
                            throw ex;
                        }

                        break;
                    }
                case Constants.ImportSettings.EnvoyImporter:
                    {
                        IsBusy = true;

                        EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

                        try
                        {
                            envoyService.ImportStoreMasterStep2Completed += new EventHandler<EnvoyImporterService.ImportStoreMasterStep2CompletedEventArgs>(envoyService_ImportStoreMasterStep2Completed);
                            envoyService.ImportStoreMasterStep2Async(WorkspaceData.Instance.RangeReview);
                        }
                        catch (Exception ex)
                        {
                            envoyService.Abort();
                            throw ex;
                        }

                        break;
                    }
            }


            OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
        }

        private void RunStep3()
        {
            EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

            try
            {
                envoyService.ImportStoreMasterStep3Completed += new EventHandler<ImportStoreMasterStep3CompletedEventArgs>(envoyService_ImportStoreMasterStep3Completed);
                envoyService.ImportStoreMasterStep3Async(WorkspaceData.Instance.RangeReview);
            }
            catch (Exception ex)
            {
                envoyService.Abort();
                throw ex;
            }


            IsBusy = true;
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
        }
        
        private void RunStep4()
        {
            EnvoyImporterServiceClient envoyService = new EnvoyImporterServiceClient();

            try
            {
                envoyService.ImportStoreMasterStep4Completed += new EventHandler<ImportStoreMasterStep4CompletedEventArgs>(envoyService_ImportStoreMasterStep4Completed);
                envoyService.ImportStoreMasterStep4Async(WorkspaceData.Instance.RangeReview);
            }
            catch (Exception ex)
            {
                envoyService.Abort();
                throw ex;
            }

            IsBusy = true;
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
        }


        void envoyService_ImportStoreMasterStep1Completed(object sender, EnvoyImporterService.ImportStoreMasterStep1CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep1Callback(e.Result);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                IsBusy = false;
                OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
                throw e.Error;
            }
        }

        void envoyService_ImportStoreMasterStep2Completed(object sender, EnvoyImporterService.ImportStoreMasterStep2CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep2Callback(e.Result);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                IsBusy = false;
                OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
                throw e.Error;
            }
        }

        void envoyService_ImportStoreMasterStep3Completed(object sender, EnvoyImporterService.ImportStoreMasterStep3CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step3ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step3ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }

                    if (model.Results.Any(r => r.ItemId != 0))
                    {
                        
                    }
                }
                else
                {
                    model.TempStores.Clear();
                }

                OnPropertyChanged<StoresImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<StoresImporterViewModel>(p => p.Step3ImagePath);
                OnPropertyChanged<StoresImporterViewModel>(p => p.TempStores);
                OnPropertyChanged<StoresImporterViewModel>(p => p.Results);
                OnPropertyChanged<StoresImporterViewModel>(p => p.IsVisibleTempStoresGV);
                OnPropertyChanged<StoresImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }

            
        }

        void envoyService_ImportStoreMasterStep4Completed(object sender, EnvoyImporterService.ImportStoreMasterStep4CompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Results = e.Result;

                Step4ImagePath = "/Images/Pass-16.png";
                HasPassedCurrentStep = true;

                if (model.Results.Any())
                {
                    if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                    {
                        Step4ImagePath = "/Images/NotPass-16.png";
                        HasPassedCurrentStep = false;
                    }
                }

                OnPropertyChanged<StoresImporterViewModel>(p => p.HasPassedCurrentStep);
                OnPropertyChanged<StoresImporterViewModel>(p => p.Step4ImagePath);
                OnPropertyChanged<StoresImporterViewModel>(p => p.Results);
                OnPropertyChanged<StoresImporterViewModel>(p => p.IsVisibleResultsGV);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }

            
        }


        void excelService_ImportStoreMasterStep1Completed(object sender, ExcelImporterService.ImportStoreMasterStep1CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep1Callback(e.Result);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                IsBusy = false;
                OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
                throw e.Error;
            }
        }

        void excelService_ImportStoreMasterStep2Completed(object sender, ExcelImporterService.ImportStoreMasterStep2CompletedEventArgs e)
        {
            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                RunStep2Callback(e.Result);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                IsBusy = false;
                OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
                throw e.Error;
            }
        }


        private void RunStep1Callback(List<ImporterResult> results)
        {
            model.Results = results;

            Step1ImagePath = "/Images/Pass-16.png";
            HasPassedCurrentStep = true;

            if (model.Results.Any())
            {
                if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                {
                    Step1ImagePath = "/Images/NotPass-16.png";
                    HasPassedCurrentStep = false;
                }
            }

            IsBusy = false;
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
            OnPropertyChanged<StoresImporterViewModel>(p => p.HasPassedCurrentStep);
            OnPropertyChanged<StoresImporterViewModel>(p => p.Step1ImagePath);
            OnPropertyChanged<StoresImporterViewModel>(p => p.Results);
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsVisibleResultsGV);
        }

        private void RunStep2Callback(List<ImporterResult> results)
        {
            model.Results = results;

            Step2ImagePath = "/Images/Pass-16.png";
            HasPassedCurrentStep = true;

            if (model.Results.Any())
            {
                if (model.Results.Any(p => p.ErrorType == ErrorType.Error))
                {
                    Step2ImagePath = "/Images/NotPass-16.png";
                    HasPassedCurrentStep = false;
                }
            }

            IsBusy = false;
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsBusy);
            OnPropertyChanged<StoresImporterViewModel>(p => p.HasPassedCurrentStep);
            OnPropertyChanged<StoresImporterViewModel>(p => p.Step2ImagePath);
            OnPropertyChanged<StoresImporterViewModel>(p => p.Results);
            OnPropertyChanged<StoresImporterViewModel>(p => p.IsVisibleResultsGV);
        }

        
    }
}
